import React, { useMemo, useState } from 'react';
import { useChatBox } from '@/components/ChatBox';
import type { ChatItemType } from '@fastgpt/global/core/chat/type.d';
import { Menu, MenuButton, MenuList, MenuItem, Box } from '@chakra-ui/react';
import { SettingsIcon, LinkIcon } from '@chakra-ui/icons';
import { useToast } from '@/web/common/hooks/useToast';
import { useTranslation } from 'next-i18next';
import MyIcon from '@fastgpt/web/components/common/Icon';
import { useRouter } from 'next/router';
import { AppSchema } from '@fastgpt/global/core/app/type.d';
import InfoModal from './Setting/infoModal';
import { useQuery } from '@tanstack/react-query';
import { useAppStore } from '@/web/core/app/store/useAppStore';
const ToolMenu = ({ history }: { history: ChatItemType[] }) => {
  const { t } = useTranslation();
  const { onExportChat } = useChatBox();
  const router = useRouter();
  const { appId = '' } = router.query as { appId: string };
  const [settingAppInfo, setSettingAppInfo] = useState<AppSchema>();
  const { appDetail, loadAppDetail } = useAppStore();
  const { toast } = useToast();

  useQuery(
    [appId],
    () => {
      appId && loadAppDetail(appId, true);
    },
    {
      onError(err: any) {
        // toast({
        //   title: err?.message || '获取应用异常',
        //   status: 'error'
        // });
      },
      onSettled() {}
    }
  );
  const menuList = useMemo(
    () => [
      {
        icon: 'core/chat/chatLight',
        label: t('core.chat.New Chat'),
        onClick: () => {
          router.replace({
            query: {
              ...router.query,
              chatId: ''
            }
          });
        }
      },
      {
        icon: 'core/app/appApiLight',
        label: `HTML ${t('Export')}`,
        onClick: () => onExportChat({ type: 'html', history })
      },
      {
        icon: 'file/markdown',
        label: `Markdown ${t('Export')}`,
        onClick: () => onExportChat({ type: 'md', history })
      },
      {
        icon: 'file/pdf',
        label: `PDF ${t('Export')}`,
        onClick: () => onExportChat({ type: 'pdf', history })
      }
    ],
    [history, onExportChat, router]
  );

  return (
    <>
      <Menu>
        {appId && appDetail.isOwner && (
          <MenuButton
            _hover={{ bg: 'myWhite.600  ' }}
            cursor={'pointer'}
            borderRadius={'md'}
            onClick={(e) => {
              e.stopPropagation();
            }}
          >
            <LinkIcon boxSize={8} p={2} color={'#575B66'} />
          </MenuButton>
        )}

        {appId && appDetail.isOwner && (
          <MenuButton
            _hover={{ bg: 'myWhite.600  ' }}
            cursor={'pointer'}
            borderRadius={'md'}
            onClick={() => {
              setSettingAppInfo(appDetail);
              return false;
            }}
          >
            <SettingsIcon boxSize={8} p={2} color={'#575B66'} />
          </MenuButton>
        )}
      </Menu>
      <Menu autoSelect={false} isLazy>
        {history.length > 0 ? (
          <>
            <MenuButton
              _hover={{ bg: 'myWhite.600  ' }}
              cursor={'pointer'}
              borderRadius={'md'}
              onClick={(e) => {
                e.stopPropagation();
              }}
            >
              <MyIcon name={'more'} w={'14px'} p={2} />
            </MenuButton>
            <MenuList color={'myGray.700'} minW={`120px !important`} zIndex={10}>
              {menuList.map((item) => (
                <MenuItem key={item.label} onClick={item.onClick} py={[2, 3]}>
                  <MyIcon name={item.icon as any} w={['14px', '16px']} />
                  <Box ml={[1, 2]}>{item.label}</Box>
                </MenuItem>
              ))}
            </MenuList>
          </>
        ) : (
          <Box w={'0'} h={'28px'} />
        )}
      </Menu>
      {appId && settingAppInfo && appDetail.isOwner && (
        <InfoModal defaultApp={settingAppInfo} onClose={() => setSettingAppInfo(undefined)} />
      )}
    </>
  );
};

export default ToolMenu;
